package kr.hkit.powerjava.chapter24.work1;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class StudentDAO implements InterfaceDAO<Student>{
	private ArrayList<Student> list;
	private static final String FILE_NAME = "studentList.dat";	//파일 이름 상수로 줌
	
	@Override
	public void insertItem(Student item) {
		if(!list.contains(item)) {
			list.add(item);
		} else {
			System.out.println("중복된 데이터");
		}
	}

	@Override
	public void deleteItem(Student item) {	//idx는 삭제를 하여야할 학번
		list.remove(item);
	}

	@Override
	public void updateItem(Student item) {
		list.set(list.indexOf(item), item);
	}

	@Override
	public Student searchItem(Student item) {
		return list.get(list.indexOf(item));	//없는 사람 null
	}

	@Override
	public void prnItemList(Comparator<Student> comp) {
		if(comp == null) {
			Collections.sort(list);
		} else {
			Collections.sort(list, comp);
		}
		
		for(Student std : list) {
			System.out.println(std);
		}
		
	}

	@Override
	public void loadFile() {
		ObjectInputStream ois = null;
		
		try {
			ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream(StudentDAO.FILE_NAME)));
			list = (ArrayList<Student>) ois.readObject();
		
		} catch (FileNotFoundException e) {	//처음 실행시켰을 때
			try {
				new File(StudentDAO.FILE_NAME).createNewFile();
				list = new ArrayList<>();
			} catch (IOException e1) {}
		} catch (Exception e) {			
			e.printStackTrace();
		} finally {
			if(ois != null) try{ois.close();}catch(Exception e){}
		}
	}

	@Override
	public void saveFile() {
		ObjectOutputStream oos = null;
		try {
			oos = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(StudentDAO.FILE_NAME)));
			oos.writeObject(list);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(oos != null) try{oos.close();}catch(Exception e){}
		}
	}
}